package com.kotlin.android.app.ui.guide

import android.app.Activity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.kotlin.android.app.AppViewModel
import com.kotlin.android.app.R
import com.kotlin.android.app.constant.KEY_HAS_SHOW_GUIDE
import com.kotlin.android.app.databinding.ActGuideBinding
import com.kotlin.android.app.handFlashAD
import com.kotlin.android.core.BaseVMActivity
import com.kotlin.android.ktx.ext.click.onClick
import com.kotlin.android.ktx.ext.datastore.DataStoreExt
import com.kotlin.android.ktx.ext.immersive.immersive
import com.kotlin.android.media.image.coil.loadImage

/**
 * 向导页
 */
class GuideActivity : BaseVMActivity<AppViewModel, ActGuideBinding>() {
    private val guideImages = arrayListOf(
        R.drawable.guide_1
    )

    override fun initTheme() {
        super.initTheme()
        immersive()
            .transparentStatusBar(isFitsSystemWindows = false)
            .statusBarDarkFont(true)
    }

    override fun initView() {
        mBinding?.viewPager?.apply {
            adapter = GuideViewPager(activity = this@GuideActivity, guideImages)
        }
    }

    inner class GuideViewPager(
        private val activity: Activity,
        private val list: ArrayList<Int>
    ) : PagerAdapter() {
        override fun getCount(): Int = list.size

        override fun isViewFromObject(view: View, obj: Any): Boolean = view == obj

        override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
            (container as ViewPager).removeView(obj as View)
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val guideView = LayoutInflater.from(activity).inflate(R.layout.item_guide, null)
            val guideIv = guideView.findViewById<AppCompatImageView>(R.id.guideIv)
            guideIv.loadImage(list[position], useProxy = false)
            if (position == list.size - 1) {
                guideIv.onClick {
                    DataStoreExt.putSyncData(KEY_HAS_SHOW_GUIDE, true)
                    activity.handFlashAD()
                    finish()
                }
            }
            (container as ViewPager).addView(guideView, 0)
            return guideView
        }
    }

    override fun initData() {
    }

    override fun startObserve() {
    }

    /**
     * 屏蔽返回按钮
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true
        }
        return false
    }
}

